﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MyOA.BLL;
using MyOA.Model;
namespace MyOA.UI.SysManage.RoleManage
{
    public partial class DistributeRole : System.Web.UI.Page
    {
        DistributeRoleManage manage = null;
        IList<SysFun> getSysFunByRoleName = null;
        /// <summary>
        /// 绑定父repeater控件
        /// </summary>
        public void dataBind()
        {
            IList<SysFun> mainMenu = null;
            if (Cache["MainMenu"] != null)
            {
                mainMenu = (IList<SysFun>)Cache["MainMenu"];
            }
            else
            {
                mainMenu = manage.getMainMenu();
                //添加缓存
                Cache.Insert("MainMenu", mainMenu, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);//把数据放入缓存
            }
            rpParent.DataSource = mainMenu;
            rpParent.DataBind();

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["loginId"] != null)
            {
              
                if (!IsPostBack)
                {


                    if (Request.QueryString["roleName"] != null && Request.QueryString["roleId"] != null)
                    {
                        string roleName = Server.UrlDecode((string)Request.QueryString["roleName"]);
                        lblRoleName.Text = roleName;



                        //实例化具有参数构造函数的物理层实例对象
                        manage = new DistributeRoleManage(roleName);

                        //获取当前角色所拥有的权限集合
                        getSysFunByRoleName = manage.getMainMenuByRoleName();

                        //绑定父菜单
                        dataBind();
                    }
                }
            }
            else
            {
                Response.Redirect("~/Login.aspx");
            }
        }

        /// <summary>
        /// 父repeater控件生成项时发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rpParent_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            HiddenField hfdNodeId = e.Item.FindControl("hfdNodeId") as HiddenField;
            //对父菜单的CHECKBOX进行赋值
            int id = int.Parse(hfdNodeId.Value);






            IList<SysFun> childrenMenu = null;
            if (Cache["childrenMenu" + id] != null)
            {
                childrenMenu = (IList<SysFun>)Cache["childrenMenu" + id];
            }
            else
            {
                childrenMenu = manage.getChildrenMenusByMainMenuId(id);
                //添加缓存
                Cache.Insert("childrenMenu" + id, childrenMenu, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);//把数据放入缓存
            }

            //把父菜单的ID放在SESSION里在子repeater控件的生成事件里取出
            Session["MainMenuId"] = id;
            foreach (SysFun sysFun in getSysFunByRoleName)
            {
                if (sysFun.NodeId == id)
                {
                    CheckBox cb = e.Item.FindControl("cbParent") as CheckBox;
                    cb.Checked = true;
                    break;
                }
            }
            //获取选中菜单的集合 放入缓存中 以便子repeater控件里获取
            IList<SysFun> checkedChildrenMenu = null;
            checkedChildrenMenu = manage.getChildrenMenusByRoleNameAndMainMenuId(id);
            Cache.Insert("checkedChildrenMenu" + id, checkedChildrenMenu, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);
            //对子repeater控件进行数据绑定
            Repeater rpChildren = e.Item.FindControl("rpChildren") as Repeater;
            rpChildren.DataSource = childrenMenu;
            rpChildren.DataBind();



        }

        /// <summary>
        /// 子repeater控件生成项时发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rpChildren_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //对子菜单的CHECKBOX进行赋值
            HiddenField hfdChildrenNodeId = e.Item.FindControl("hfdChildrenNodeId") as HiddenField;
            int id = int.Parse(hfdChildrenNodeId.Value);
            if (Session["MainMenuId"] != null)
            {
                int mainMenuId = (int)Session["MainMenuId"];
                IList<SysFun> checkedChildrenMenu = null;

                if (Cache["checkedChildrenMenu" + mainMenuId] != null)
                {
                    checkedChildrenMenu = (IList<SysFun>)Cache["checkedChildrenMenu" + mainMenuId];
                }
                else
                {
                    checkedChildrenMenu = manage.getChildrenMenusByRoleNameAndMainMenuId(mainMenuId);
                }
                foreach (SysFun sysFun in checkedChildrenMenu)
                {
                    if (sysFun.NodeId == id)
                    {
                        CheckBox cb = e.Item.FindControl("cbChildren") as CheckBox;
                        cb.Checked = true;
                        break;

                    }
                }




            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int roleId = int.Parse(Request.QueryString["roleId"]);
            string roleName = Server.UrlDecode((string)Request.QueryString["roleName"]);
            //实例化具有参数构造函数的物理层实例对象
            manage = new DistributeRoleManage(roleName);
            //获取此角色的所有权限ID集合
            IList<RoleRight> roleRight = manage.getRoleRightByRoleId(roleId);
            //当前选中的要增加信息(全打钩的权限)
            IList<RoleRight> currentInsertRoleRight = new List<RoleRight>();
            //当前没选中的要删除信息（不打钩的权限）
            IList<RoleRight> currentDeleteRoleRight = new List<RoleRight>();

            foreach (RepeaterItem parentItem in rpParent.Items)
            {
                CheckBox cbParent = parentItem.FindControl("cbParent") as CheckBox;
                HiddenField hfdParent = parentItem.FindControl("hfdNodeId") as HiddenField;
                Repeater rpChildren = parentItem.FindControl("rpChildren") as Repeater;
                if (cbParent.Checked)
                {
                    RoleRight parentInsertRoleRight = new RoleRight();
                    //sysFun.DisplayName = cbParent.Text;
                    parentInsertRoleRight.Node.NodeId = int.Parse(hfdParent.Value);

                    //选中的话就添加到集合里
                    currentInsertRoleRight.Add(parentInsertRoleRight);

                    foreach (RepeaterItem childrenItem in rpChildren.Items)
                    {
                        CheckBox cbChildren = childrenItem.FindControl("cbChildren") as CheckBox;
                        HiddenField hfdChildren = childrenItem.FindControl("hfdChildrenNodeId") as HiddenField;
                        if (cbChildren.Checked)
                        {
                            RoleRight childInsertRoleRight = new RoleRight();
                            childInsertRoleRight.Node.NodeId = int.Parse(hfdChildren.Value);
                            //childSysFun.DisplayName = cbChildren.Text;

                            //选中的话就添加到集合里
                            currentInsertRoleRight.Add(childInsertRoleRight);
                        }
                        else
                        {
                            //没选中的话就加到DELETE集合
                            RoleRight childDeleteRoleRight = new RoleRight();
                            childDeleteRoleRight.Node.NodeId = int.Parse(hfdChildren.Value);

                            currentDeleteRoleRight.Add(childDeleteRoleRight);
                        }
                    }

                }
                else
                {
                    //没选中的话就加到DELETE集合
                    RoleRight parentDeleteRoleRight = new RoleRight();
                    parentDeleteRoleRight.Node.NodeId = int.Parse(hfdParent.Value);

                    currentDeleteRoleRight.Add(parentDeleteRoleRight);

                    //获取子菜单没选中的集合
                    foreach (RepeaterItem childrenItem in rpChildren.Items)
                    {
                        CheckBox cbChildren = childrenItem.FindControl("cbChildren") as CheckBox;
                        HiddenField hfdChildren = childrenItem.FindControl("hfdChildrenNodeId") as HiddenField;
                        if (cbChildren.Checked == false)
                        {
                            //没选中的话就加到DELETE集合
                            RoleRight childDeleteRoleRight = new RoleRight();
                            childDeleteRoleRight.Node.NodeId = int.Parse(hfdChildren.Value);

                            currentDeleteRoleRight.Add(childDeleteRoleRight);
                        }
                    }
                }
            }
            //取出不需要增加或要删除的ID     
            IList<int> listNoInsertId = new List<int>();
            IList<int> listDeleteId = new List<int>();

            //判断哪个集合大就决定外循环是哪个 这样提高循环效率
            if (currentDeleteRoleRight.Count >= roleRight.Count)
            {
                foreach (RoleRight delete in currentDeleteRoleRight)
                {
                    foreach (RoleRight dataBase in roleRight)
                    {
                        if (dataBase.Node.NodeId == delete.Node.NodeId)
                        {
                            listDeleteId.Add(dataBase.Node.NodeId);
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (RoleRight dataBase in roleRight)
                {
                    foreach (RoleRight delete in currentDeleteRoleRight)
                    {
                        if (dataBase.Node.NodeId == delete.Node.NodeId)
                        {
                            listDeleteId.Add(dataBase.Node.NodeId);
                            break;
                        }
                    }
                }
            }

            //判断哪个集合大就决定外循环是哪个 这样提高循环效率
            if (currentInsertRoleRight.Count >= roleRight.Count)
            {
                foreach (RoleRight insert in currentInsertRoleRight)
                {
                    foreach (RoleRight dataBase in roleRight)
                    {
                        if (insert.Node.NodeId == dataBase.Node.NodeId)
                        {
                            listNoInsertId.Add(dataBase.Node.NodeId);
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (RoleRight dataBase in roleRight)
                {
                    foreach (RoleRight insert in currentInsertRoleRight)
                    {
                        if (insert.Node.NodeId == dataBase.Node.NodeId)
                        {
                            listNoInsertId.Add(dataBase.Node.NodeId);
                            break;
                        }
                    }
                }
            }



            //移除与数据库里相同的要增加的项
            IList<int> roleRightId = new List<int>();
            foreach (RoleRight item in currentInsertRoleRight)
            {
                roleRightId.Add(item.Node.NodeId);
            }
            foreach (int item in listNoInsertId)
            {
                if (roleRightId.Contains(item))
                {
                    roleRightId.Remove(item);
                }
            }

            //连接增加或删除的字符串
            string insertId = string.Empty;
            string deleteId = string.Empty;
            foreach (int insert in roleRightId)
            {
                insertId += insert + ",";
            }
            foreach (int delete in listDeleteId)
            {
                deleteId += delete + ",";
            }


            string message = string.Empty;
            //有删除或增加ID时才进行操作
            if (insertId != string.Empty || deleteId != string.Empty)
            {
                //去除最后一个逗号
                if (insertId != string.Empty)
                {
                    insertId = insertId.Substring(0, insertId.LastIndexOf(","));
                }
                if (deleteId != string.Empty)
                {
                    deleteId = deleteId.Substring(0, deleteId.LastIndexOf(","));
                }

                manage = new DistributeRoleManage();

                if (manage.insertAndRoleRight(roleId, deleteId, insertId))
                {
                    message = "修改权限成功";
                }
                else
                {
                    message = "修改权限失败";
                }
            }
            else
            {
                message = "没有进行任何操作";
            }
            string script = string.Format("<script>Alert('{0}',null,null,'温馨提示',aHref)</script>", message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);


        }




    }
}
